﻿using B.S.BasicData.API.Write.Application.Command.Menu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.API.Write.Application.Handler.Menu
{
    /// <summary>
    /// 删除菜单信息请求命令处理类
    /// </summary>
    public class DelMenuHandler : IRequestHandler<DelMenuCommand, ApiResult<int>>
    {
        IBaseRepository<MenuModel> menuRep;

        public DelMenuHandler(IBaseRepository<MenuModel> menuRep)
        {
            this.menuRep = menuRep;
        }

        public Task<ApiResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var menu = menuRep.GetAll().FirstOrDefault(x => x.Id == request.id);
                if (menu == null)
                {
                    res.Msg = "菜单信息不存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                
                

                int r = 0;
                int r1 = 0;
                using(TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {

                    // 递归删除方法
                    void DeleteMenuAndChildren(int menuId)
                    {
                        var children = menuRep.GetAll().Where(x => x.P_ID == menuId && !x.IsDeleted).ToList();
                        foreach (var child in children)
                        {
                            DeleteMenuAndChildren(child.Id);
                            child.IsDeleted = true;
                            r1 = menuRep.UpdateAsync(child).Result;
                        }
                    }

                    // 先删除所有下级
                    DeleteMenuAndChildren(menu.Id);

                    // 删除自身
                    menu.IsDeleted = true;

                    r =menuRep.UpdateAsync(menu).Result;
                    
                    tran.Complete();
                }

                if(r>0)
                {
                    res.Msg = "删除成功";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "删除失败";
                    res.Code = ApiEnum.Fail;
                }
                
                return Task.FromResult(res);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
